<template>
  <div class="w-full max-w-screen-lg mx-auto">
    <!-- flu标签显示区域 -->
    <div class="flex mb-2">
      <template v-for="(segment, index) in sortedData" :key="index">
        <div class="text-sm font-bold" :style="{ width: `${getWidthPercentage(segment.bpp)}%` }">
          <span class="flex justify-center">{{ segment.flu }}</span>
        </div>
      </template>
    </div>

    <!-- 条形图容器 -->
    <div class="relative h-8 overflow-hidden bg-gray-200 border border-gray-300 rounded-lg">
      <template v-for="(segment, index) in sortedData" :key="index">
        <div
          class="absolute h-full transition-all duration-200"
          :style="{
            left: `${getLeftPosition(index)}%`,
            width: `${getWidthPercentage(segment.bpp)}%`,
            backgroundColor: getFluColor(segment.flu)
          }"
        />
      </template>
    </div>

    <!-- 底部数值显示 -->
    <div class="relative h-8 mt-2">
      <span class="absolute left-0 font-bold transform -translate-x-1/2 top-4">0</span>
      <template v-for="(segment, index) in sortedData" :key="index">
        <span
          class="absolute font-bold transform -translate-x-1/2"
          :style="{ left: `${getLeftPosition(index) + getWidthPercentage(segment.bpp)}%` }"
        >
          {{ getCumulativeDistance(index).toFixed(2) }}
        </span>
      </template>
    </div>
    <div class="-mt-6 text-lg font-bold text-center">km</div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

const props = defineProps({
  batchData: {
    type: Array,
    required: true
  },
  batchDataTy: {
    type: Array,
    required: true
  },
  wb_oil: {
    type: String,
    default: 'WEHY'
  },
  currentTime: {
    type: Number,
    default: 0
  },
  isPlaying: {
    type: Boolean,
    default: true
  },
  timeInterval: {
    type: Number,
    default: 5
  }
})

// 当前数据索引计算
const currentIndex = computed(() => {
  if (!props.batchData?.length) return 0
  return Math.min(Math.floor(props.currentTime / props.timeInterval), props.batchData.length - 1)
})

// 获取当前批次数据
const currentData = computed(() => props.batchData[currentIndex.value])
const currentData_ty = computed(() =>
  props.batchDataTy?.length ? props.batchDataTy[currentIndex.value] || [] : []
)

// 提取并处理管段数据
const extractSegments = (data, prefix = '') => {
  if (!data) return []
  return Array.from({ length: 8 }, (_, i) => i + 1)
    .filter((i) => data[`bpp_${i}`])
    .map((i) => ({
      bpp: parseFloat(data[`bpp_${i}`]),
      flu: data[`flu_${i}`]
    }))
}

// 合并并排序所有管段数据
const sortedData = computed(() => {
  const segments = extractSegments(currentData.value)

  if (props.batchDataTy?.length) {
    // 添加前缀段
    segments.push({
      bpp: 26.6,
      flu: props.wb_oil
    })
    // 添加后缀段
    segments.push(...extractSegments(currentData_ty.value))
  }

  return segments.sort((a, b) => a.bpp - b.bpp)
})

// 计算总长度
const totalLength = computed(
  () => sortedData.value.reduce((sum, segment) => sum + segment.bpp, 0) || 1
)

// 计算宽度百分比
const getWidthPercentage = (value) => (value / totalLength.value) * 100

// 计算左侧位置
const getLeftPosition = (index) => {
  return sortedData.value
    .slice(0, index)
    .reduce((sum, segment) => sum + getWidthPercentage(segment.bpp), 0)
}

// 计算累计距离
const getCumulativeDistance = (index) => {
  return sortedData.value.slice(0, index + 1).reduce((sum, segment) => sum + segment.bpp, 0)
}

// 颜色管理
const baseColors = [
  '#2ecc71',
  '#3498db',
  '#e74c3c',
  '#9b59b6',
  '#f1c40f',
  '#a3b9d2',
  '#af49d2',
  '#d599d2'
]
const colorMap = ref({})

const getFluColor = (flu) => {
  if (!colorMap.value[flu]) {
    const usedColorCount = Object.keys(colorMap.value).length
    colorMap.value[flu] = baseColors[usedColorCount % baseColors.length]
  }
  return colorMap.value[flu]
}

// 刷新颜色映射
const refreshData = () => {
  colorMap.value = {}
  const allFluLabels = new Set()

  // 收集所有flu标签
  props.batchData?.forEach((batch) => {
    Array.from({ length: 8 }, (_, i) => i + 1).forEach((i) => {
      const flu = batch[`flu_${i}`]
      if (flu) allFluLabels.add(flu)
    })
  })

  if (props.batchDataTy?.length) {
    allFluLabels.add(props.wb_oil)
    props.batchDataTy.forEach((batch) => {
      Array.from({ length: 8 }, (_, i) => i + 1).forEach((i) => {
        const flu = batch[`flu_${i}`]
        if (flu) allFluLabels.add(flu)
      })
    })
  }

  // 分配颜色
  Array.from(allFluLabels).forEach((flu, index) => {
    colorMap.value[flu] = baseColors[index % baseColors.length]
  })
}

// 监听数据变化
watch(() => props.batchData, refreshData, { immediate: true })

defineExpose({ refreshData })
</script>
